<script setup lang="ts">
import { ref, computed } from 'vue'
import { ElDropdown, ElDropdownMenu, ElDropdownItem, ElMessageBox } from 'element-plus'
import { useI18n } from '@/hooks/web/useI18n'
import { useCache } from '@/hooks/web/useCache'
import { resetRouter } from '@/router'
import { useRouter } from 'vue-router'
import { loginOutApi } from '@/api/login'
import { useDesign } from '@/hooks/web/useDesign'
import { useTagsViewStore } from '@/store/modules/tagsView'
import { useAppStore } from '@/store/modules/app'
import { useBasicStoreWithOut } from '@/store/modules/basic'
import { useNotificationStore } from '@/store/modules/notification'

const tagsViewStore = useTagsViewStore()

const { getPrefixCls } = useDesign()

const prefixCls = getPrefixCls('user-info')

const { t } = useI18n()

const basicStore = useBasicStoreWithOut()

const appStore = useAppStore()

const { wsCache } = useCache()

const { replace, push } = useRouter()

const notificationStore = useNotificationStore()

const userInfo = computed(() => wsCache.get(appStore.getUserInfo))

const isLoginVerify = computed(() => basicStore.getIsLoginVerify)

const canModifyPassword = computed(() => basicStore.getLogin?.modifypassword)

const loginOut = () => {
  ElMessageBox.confirm(t('common.loginOutMessage'), t('common.reminder'), {
    confirmButtonText: t('common.ok'),
    cancelButtonText: t('common.cancel'),
    type: 'warning'
  })
    .then(async () => {
      await loginOutApi().catch(() => {})
      notificationStore.close()
      wsCache.clear()
      tagsViewStore.delAllViews()
      resetRouter() // 重置静态路由表
      replace({ path: '/login' })
    })
    .catch(() => {})
}

const goModifyPassword = () => {
  push({ path: '/modifypassword' })
}

let isAvatarExist = ref(true)
</script>

<template>
  <ElDropdown :class="prefixCls" trigger="click">
    <div class="flex items-center">
      <img
        v-if="userInfo.avatar && isAvatarExist"
        :src="userInfo.avatar"
        alt=""
        @error="isAvatarExist = false"
        class="w-[calc(var(--logo-height)-25px)] rounded-[50%]"
      />
      <Icon
        v-else
        icon="svg-icon:avatar"
        :size="20"
        class="w-[calc(var(--logo-height)-25px)] rounded-[50%]"
      />
      <span class="<lg:hidden text-14px pl-[5px] text-[var(--top-header-text-color)]">
        {{ userInfo.name }}
      </span>
    </div>
    <template #dropdown>
      <ElDropdownMenu v-if="isLoginVerify">
        <ElDropdownItem v-if="canModifyPassword">
          <div @click="goModifyPassword">{{ t('common.modifypassword') }}</div>
        </ElDropdownItem>
        <ElDropdownItem>
          <div @click="loginOut">{{ t('common.loginOut') }}</div>
        </ElDropdownItem>
      </ElDropdownMenu>
    </template>
  </ElDropdown>
</template>
